package cn.edu.nhic.order;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.edu.nhic.order.adapter.ShopAdapter;
import cn.edu.nhic.order.bean.ShopBean;
import cn.edu.nhic.order.util.Constant;
import cn.edu.nhic.order.util.JsonParse;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 店铺列表
 */
public class ShopActivity extends AppCompatActivity {
    private ListView shopListView;
    private List<ShopBean> shopBeanList;
    private MsgHandler msgHandler;
    private ShopAdapter shopAdapter;
    private JsonParse jsonParse;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        msgHandler=new MsgHandler();
        jsonParse=JsonParse.getInstance();
        //1.初始化视图
        this.initView();
        //2.初始化数据
//        this.initData();
        this.initData1();
        //3.初始化适配器
        this.initAdapter();

        //4.初始化事件
//        this.initEvent();
    }
    //1.初始化视图
    public void initView(){
        this.shopListView=this.findViewById(R.id.shop_listView);
    }
    //2.初始化数据
    //从网络读取JSON数据并解析后加入ArrayList集合中
    public void initData1(){
        this.shopBeanList=new ArrayList<ShopBean>();
        //知识点1:网络访问 步骤
        //1.创建OkHttpClient对象
        OkHttpClient client=new OkHttpClient();
        //2.构建Request对象
//        String url="http://192.168.3.195:8080/order/shop_list_data.json";
        String url= Constant.WEB_SITE+Constant.REQUEST_SHOP_URL;
        Request request=new Request.Builder()
                .url(url)
                .get()
                .build();
        //3.通过OkHttpClient对象创建一个Call对象  呼叫
        Call call=client.newCall(request);
        //加入队列异步网络请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json=response.body().string();
//                System.out.println("========子线程中网络访问响应的数据======="+json);
                Message msg=new Message();
                msg.what=1; //消息的标志位，可以自定义
                msg.obj=json;
                msgHandler.sendMessage(msg); //从子线程中发送消息到主线程ShopActiviy
            }
        });
    }
    //本地数据
    public void initData(){
        this.shopBeanList=new ArrayList<ShopBean>();
        ShopBean sb1=new ShopBean();
        sb1.setShopName("柠檬可乐");
        sb1.setSaleNum(2476);
        sb1.setOfferPrice(new BigDecimal(20));
        sb1.setDistributionCost(new BigDecimal(2.5));
        sb1.setTime("配送15分钟");
        sb1.setFeature("南华大道回头率第2名");
        this.shopBeanList.add(sb1);
        ShopBean sb2=new ShopBean();
        sb2.setShopName("COCO都可");
        sb2.setSaleNum(2123);
        sb2.setOfferPrice(new BigDecimal(15));
        sb2.setDistributionCost(new BigDecimal(2));
        sb2.setTime("配送10分钟");
        sb2.setFeature("南华大道回头率第1名");
        this.shopBeanList.add(sb2);
        ShopBean sb3=new ShopBean();
        sb3.setShopName("维尔纳斯");
        sb3.setSaleNum(1234);
        sb3.setOfferPrice(new BigDecimal(21));
        sb3.setDistributionCost(new BigDecimal(3.5));
        sb3.setTime("配送8分钟");
        sb3.setFeature("南华大道回头率第3名");
        this.shopBeanList.add(sb3);
        ShopBean sb4=new ShopBean();
        sb4.setShopName("千层蛋糕");
        sb4.setSaleNum(2476);
        sb4.setOfferPrice(new BigDecimal(15));
        sb4.setDistributionCost(new BigDecimal(2));
        sb4.setTime("配送10分钟");
        sb4.setFeature("南华大道回头率第4名");
        this.shopBeanList.add(sb4);
    }
    //3.初始化适配器
    public void initAdapter(){
        shopAdapter=new ShopAdapter(this,R.layout.shop_item,this.shopBeanList);
        this.shopListView.setAdapter(shopAdapter);
    }
    //4.初始化事件
    public void initEvent(){
        this.shopListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(),"测试1",Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * Handler 异步回调机制Handler助手类
     */
    class MsgHandler extends Handler{
        /**
         * dispatch 分配分发
         * @param msg
         */
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
            //以下子线程网络访问响应传递给主线ShopActivity的消息处理代码段
            String shopJson=(String)msg.obj;
            System.out.println("======MsgHandler传递消息到主线程中 消息为：======"+shopJson);
//            //解析JSON数据 ，google开发的专用JSON解析工具gson
//            //步骤：1生成gson对象
//            Gson gson=new Gson();
//            //步骤：2生成Type对象 用来对象反射的
//            Type type= new TypeToken<List<ShopBean>>(){}.getType();
//            shopBeanList=gson.fromJson(shopJson,type);
            shopBeanList=jsonParse.getShopBeanList(shopJson);
            //注意很重要 ：重新设置下ShopAdapter的数据源
            shopAdapter.setData(shopBeanList);
        }
    }
}